|
|
|
|
|
|
|
|
In the preceding example, 1 is the file number. However, if you open and close multiple files throughout your program, using this number might not be a good idea. In that case, you should use the FreeFile function, which returns the next available file number, as in the following example: |
|
|
|
|
|
|
|
|
Dim nFile As Integer
nFile = FreeFile
Open "C:\MYFILE.TXT" for Input As #nFile  |
|
|
|
|
|
|
|
|
|
|
After you finish using a file, you should close it with the Close statement (refer to Listing 21.1). This way, you can free up the file number for use with other files. |
|
|
|
|
|
|
|
|
In addition to providing the filename and number association, the Open statement tells Visual Basic how you intend to use the specified file. (Many different options are available with the Open statement, as discussed in the Help file.) |
|
|
|
|
| |
|
|
|
|
Before you open a file for input, use the Dir$ function to see whether it actually exists. |
|
|
|
|
|
|
|
|
|
|
The keyword Input indicates that the file will be opened for Sequential Input, which means that you can only move forward through the file in sequence. The act of reading information from the file automatically moves an internal file pointer forward for the next read. The code in Listing 21.1 uses a Line Input statement in a While loop to read information. The first Line Input statement reads the first line, the second Line Input reads the second line, and so on. A line in a file is delimited by an end of line marker, which in Windows is the carriage return character followed by the line feed character. The syntax of the Line Input statement is |
|
|
|
|
|
|
|
|
Line Input #filenumber,variablename |
|
|
|
|
|
|
|
|
where filenumber is an open file number and variablename is a string or variant variable. If you try to read more lines of text than are in the file, an error occurs. Therefore, you should use the EOF (end-of-file) function to check whether you have reached the end of file before attempting to read again. |
|
|
|
|
|
|
|
|
After you open the file, you can choose from several methods of reading information from it. In the example, each name is the only piece of information on each line, so no further processing on the string variable is necessary. However, sometimes you may want to read less than a whole line or store more than one piece of information on a single line. In these cases, you can use the Input # statement or the Input function. |
|
|
|
|
|
|
|
|
The Input # statement is designed to read information stored in a delimited fashion. For example, the following line of a text file contains three distinct pieces of information: a string, a number, and a date. Commas, quotation marks, and the # symbol are used to delimit the information. |
|
|
|
|
|
|
|
|
The following line of code correctly reads each item from the file into the appropriate variables: |
|
|
|
|
|
|
|
|
Input #1, stringvar, intvar, datevar |
|
|
|
|
|